{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "d8168ef5",
   "metadata": {},
   "source": [
    "## 方式一：函数计时-函数装饰器"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "2163f98a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Function: test start...]\n",
      "[Function: test finished, spent time: 1.51s]\n"
     ]
    }
   ],
   "source": [
    "from functools import wraps\n",
    "import time\n",
    "\n",
    "def func_timer(function):\n",
    "    '''\n",
    "    用装饰器实现函数计时\n",
    "    :param function: 需要计时的函数\n",
    "    :return: None\n",
    "    '''\n",
    "    @wraps(function)\n",
    "    def function_timer(*args, **kwargs):\n",
    "        print('[Function: {name} start...]'.format(name = function.__name__))\n",
    "        t0 = time.time()\n",
    "        result = function(*args, **kwargs)\n",
    "        t1 = time.time()\n",
    "        print('[Function: {name} finished, spent time: {time:.2f}s]'.format(name = function.__name__,time = t1 - t0))\n",
    "        return result\n",
    "    return function_timer\n",
    "\n",
    "@func_timer\n",
    "def test():\n",
    "    time.sleep(1.5)\n",
    "\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    test()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d6f16c66",
   "metadata": {},
   "source": [
    "## 方式二：代码片段计时——上下文管理器"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "f914467e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "do something\n",
      "[time spent: 0.00s]\n"
     ]
    }
   ],
   "source": [
    "from functools import wraps\n",
    "import time\n",
    "\n",
    "class Timer(object):\n",
    "    '''\n",
    "    用上下文管理器计时\n",
    "    '''\n",
    "    def __enter__(self):\n",
    "        self.t0 = time.time()\n",
    "\n",
    "    def __exit__(self, exc_type, exc_val, exc_tb):\n",
    "        print('[time spent: {time:.2f}s]'.format(time = time.time() - self.t0))\n",
    "\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    with Timer() as t:\n",
    "        print('do something')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
